<template>
    <el-dialog :visible.sync="visible" :title="title" :width="dialogWidth" :close-on-click-modal="false"
        :before-close="handleClose" class="password-reset-modal">
        <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px"
            class="password-form">
            <!-- 手机号输入框 -->
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="passwordForm.phone" type="text"
                    placeholder="请输入手机号"
                    @keyup.enter.native="handleSubmit"
                    ></el-input> <!-- 移除密码显示/隐藏的图标逻辑 -->
            </el-form-item>

            <!-- 旧密码输入框 -->
            <el-form-item label="旧密码" prop="oldPassword">
                <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入旧密码"
                    :show-password="showOldPwd" @keyup.enter.native="handleSubmit">
                    <i slot="suffix" class="el-icon-view" @click="showOldPwd = !showOldPwd"
                        :class="{ 'active': showOldPwd }"></i>
                </el-input>
            </el-form-item>

            <!-- 新密码输入框 -->
            <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码（至少8位，包含字母和数字）"
                    :show-password="showNewPwd" @input="checkPasswordStrength" @keyup.enter.native="handleSubmit">
                    <i slot="suffix" class="el-icon-view" @click="showNewPwd = !showNewPwd"
                        :class="{ 'active': showNewPwd }"></i>
                </el-input>

                <!-- 密码强度提示 -->
                <div v-if="passwordForm.newPassword" class="password-strength">
                    <div class="strength-label">密码强度：</div>
                    <div class="strength-bars">
                        <div class="strength-bar" :class="getStrengthClass(1)"></div>
                        <div class="strength-bar" :class="getStrengthClass(2)"></div>
                        <div class="strength-bar" :class="getStrengthClass(3)"></div>
                    </div>
                    <div class="strength-text">{{ strengthText }}</div>
                </div>
            </el-form-item>

            <!-- 确认密码输入框 -->
            <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"
                    :show-password="showConfirmPwd" @keyup.enter.native="handleSubmit">
                    <i slot="suffix" class="el-icon-view" @click="showConfirmPwd = !showConfirmPwd"
                        :class="{ 'active': showConfirmPwd }"></i>
                </el-input>
            </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
    </el-dialog>
</template>

<script>
export default {
    name: 'PasswordResetModal',
    props: {
        // 控制弹窗显示/隐藏
        visible: {
            type: Boolean,
            default: false
        },
        // 弹窗标题
        title: {
            type: String,
            default: '修改密码'
        },
        // 弹窗宽度
        dialogWidth: {
            type: String,
            default: '500px'
        }
    },
    data() {
        // 验证新密码与确认密码是否一致
        const validateConfirmPassword = (rule, value, callback) => {
            if (value !== this.passwordForm.newPassword) {
                callback(new Error('两次输入的密码不一致'));
            } else {
                callback();
            }
        };

        // 验证新密码强度
        const validatePasswordStrength = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入新密码'));
                return;
            }

            // 密码至少8位，包含字母和数字
            const reg = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;
            if (!reg.test(value)) {
                callback(new Error('密码至少8位，且包含字母和数字'));
                return;
            }

            callback();
        };

        return {
            // 密码表单数据
            passwordForm: {
                phone: '',
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            },
            // 表单验证规则
            passwordRules: {
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' }
                ],
                oldPassword: [
                    { required: true, message: '请输入旧密码', trigger: 'blur' }
                ],
                newPassword: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { validator: validatePasswordStrength, trigger: 'blur' }
                ],
                confirmPassword: [
                    { required: true, message: '请确认新密码', trigger: 'blur' },
                    { validator: validateConfirmPassword, trigger: 'blur' }
                ]
            },
            // 控制密码显示/隐藏
            showOldPwd: false,
            showNewPwd: false,
            showConfirmPwd: false,
            // 密码强度相关
            passwordStrength: 0, // 0-3，3为最强
            strengthText: ''
        };
    },
    methods: {
        /**
         * 检查密码强度
         */
        checkPasswordStrength() {
            const password = this.passwordForm.newPassword;
            if (!password) {
                this.passwordStrength = 0;
                this.strengthText = '';
                return;
            }

            let strength = 0;

            // 长度检查
            if (password.length >= 8) strength++;
            // 包含小写字母
            if (/[a-z]/.test(password)) strength++;
            // 包含大写字母
            if (/[A-Z]/.test(password)) strength++;
            // 包含数字
            if (/[0-9]/.test(password)) strength++;
            // 包含特殊字符
            if (/[^A-Za-z0-9]/.test(password)) strength++;

            // 转换为1-3的强度等级
            this.passwordStrength = Math.min(Math.ceil(strength / 2), 3);

            // 设置强度文本
            switch (this.passwordStrength) {
                case 1:
                    this.strengthText = '弱';
                    break;
                case 2:
                    this.strengthText = '中';
                    break;
                case 3:
                    this.strengthText = '强';
                    break;
                default:
                    this.strengthText = '';
            }
        },

        /**
         * 获取密码强度条的样式类
         */
        getStrengthClass(level) {
            if (this.passwordStrength >= level) {
                if (level === 1) return 'weak';
                if (level === 2) return 'medium';
                if (level === 3) return 'strong';
            }
            return 'empty';
        },

        /**
         * 提交表单
         */
        handleSubmit() {
            this.$refs.passwordForm.validate(valid => {
                if (valid) {
                    // 表单验证通过，提交数据
                    this.$emit('submit', {
                        phone: this.passwordForm.phone,
                        oldPassword: this.passwordForm.oldPassword,
                        newPassword: this.passwordForm.newPassword
                    });
                }
            });
        },

        /**
         * 取消操作
         */
        handleCancel() {
            this.$emit('cancel');
            this.resetForm();
        },

        /**
         * 关闭弹窗前的操作
         */
        handleClose() {
            this.$emit('update:visible', false);
            this.resetForm();
        },

        /**
         * 重置表单
         */
        resetForm() {
            if (this.$refs.passwordForm) {
                this.$refs.passwordForm.resetFields();
            }
            this.passwordStrength = 0;
            this.strengthText = '';
        }
    },
    watch: {
        // 监听弹窗显示状态，显示时重置表单
        visible(val) {
            if (!val) {
                this.resetForm();
            }
        }
    }
};
</script>

<style scoped>
.password-form {
    margin-top: 10px;
}

/* 密码强度样式 */
.password-strength {
    margin-top: 8px;
    display: flex;
    align-items: center;
    font-size: 12px;
}

.strength-label {
    color: #606266;
    margin-right: 8px;
}

.strength-bars {
    display: flex;
    width: 120px;
    height: 6px;
    margin-right: 8px;
}

.strength-bar {
    flex: 1;
    margin: 0 2px;
    border-radius: 3px;
    background-color: #e0e0e0;
    transition: background-color 0.3s;
}

.strength-bar.empty {
    background-color: #e0e0e0;
}

.strength-bar.weak {
    background-color: #f56c6c;
}

.strength-bar.medium {
    background-color: #e6a23c;
}

.strength-bar.strong {
    background-color: #67c23a;
}

.strength-text {
    color: #606266;
}

/* 密码可见图标样式 */
::v-deep .el-icon-view {
    cursor: pointer;
    color: #c0c4cc;
    transition: color 0.2s;
}

::v-deep .el-icon-view.active {
    color: #409eff;
}
</style>